<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <video
      style="opacity: 0"
      id="video"
      width="480"
      height="320"
      controls
    ></video>
    <div>
      <button id="capture">拍照</button>
    </div>
    <canvas id="canvas" width="480" height="320"></canvas>

    <script>
      let video = document.getElementById("video");
      video.muted = true;
      let canvas = document.getElementById("canvas");
      let context = canvas.getContext("2d");
      let capture = document.getElementById("capture");

      // 获取摄像头视频流
      navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: true,
        })
        .then(function (stream) {
          video.srcObject = stream;
          video.autoplay = true;
        })
        .catch(function (error) {
          console.log("Something went wrong!");
        });

      // 拍照功能
      capture.addEventListener("click", function () {
        video.play();
        setTimeout(() => {
          context.drawImage(video, 0, 0, 480, 320);
          let image = canvas.toDataURL("image/png");
          console.log(image);
        }, 100);
      });
    </script>
  </body>
</html>
